import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class SumOfFourNumbers {
    // 四数之和 https://leetcode.cn/problems/4sum/description/
    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> ret=new ArrayList<>();
        Arrays.sort(nums);
        for(int i=0;i<nums.length;) {        // a
            for(int j=i+1;j<nums.length;) {  //b
                long tmp=(long)target-nums[i]-nums[j];
                int left=j+1;
                int right=nums.length-1;
                while(left<right){
                    int sum=nums[left]+nums[right];
                    if(sum<tmp) {
                        left++;
                    }else if(sum>tmp) {
                        right--;
                    }else {
                        ret.add(new ArrayList<>(Arrays.asList(nums[i],nums[j],nums[left],nums[right])));
                        left++;
                        right--;
                        //对left和right去重
                        while(left<right && nums[left]==nums[left-1]) {
                            left++;
                        }
                        while(left<right && nums[right]==nums[right+1]) {
                            right--;
                        }
                    }
                }
                j++;
                while(j<nums.length && nums[j]==nums[j-1]) {
                    j++;
                }
            }
            i++;
            while(i<nums.length && nums[i]==nums[i-1]) {
                i++;
            }
        }
        return ret;
    }
}
